package lex.expression.tree;

import java.util.Stack;

import lex.expression.Element;
import lex.expression.PostfixExpression;


public class ExpressionTree {
	public Node parseRootNode( PostfixExpression pe )
	{
		Node root = null;
		Node first = null;
		Node second = null;
		Stack<Object> operandStask = new Stack<Object>();
		Stack<Element> postfix = pe.getPostfix();
		while( false == postfix.empty() )
		{
			Element n = postfix.pop();
			if( true == n.isOperand() )
			{
				operandStask.push( (Element) n );
				continue;
			}
			else if( true == n.isOperator() )
			{
				second = newNode( operandStask.pop() );
				first = newNode( operandStask.pop() );
				root = Node.newParentNode( n, first, second );
				operandStask.push( root );
			}
			else
			{
				System.err.println( "Unkown node: " + n );
				return root;
			}
		}
		return root;
	}

	private Node newNode(Object o) {
		if (o instanceof Node)
			return (Node) o;
		else
			return Node.newChildNode((Element) o);
	}
}
